import { defineStore } from 'pinia'
import { getAllActivities } from '@/api/activity'

export const useActivityStore = defineStore('activity', {
  state: () => ({
    // 活动列表
    activities: [],
    // 活动ID到活动对象的映射，方便快速查找
    activityMap: {},
    // 渠道ID到渠道名称的映射
    channelMap: {
      1: '线上活动',
      2: '推广介绍'
    },
    // 加载状态
    loading: false,
    // 是否已经初始化
    initialized: false
  }),

  getters: {
    // 获取所有活动列表
    allActivities: (state) => state.activities,
    
    // 根据活动ID获取活动名称
    getActivityNameById: (state) => (id) => {
      const activity = state.activityMap[id]
      return activity ? activity.name : ''
    },
    
    // 根据渠道ID获取渠道名称
    getChannelNameById: (state) => (id) => {
      return state.channelMap[id] || ''
    },
    
    // 获取活动选项（用于select组件）
    activityOptions: (state) => {
      return state.activities.map(activity => ({
        value: activity.id,
        label: activity.name
      }))
    },
    
    // 获取渠道选项（用于select组件）
    channelOptions: (state) => {
      return Object.entries(state.channelMap).map(([value, label]) => ({
        value: Number(value),
        label
      }))
    }
  },

  actions: {
    /**
     * 初始化活动数据
     * 在应用启动或登录后调用
     */
    async initializeActivities() {
      if (this.initialized || this.loading) return
      
      this.loading = true
      try {
        const response = await getAllActivities()
        if (response.code === 1) {
          const activities = response.data.rows || []
          this.activities = activities
          
          // 构建活动ID映射
          const activityMap = {}
          activities.forEach(activity => {
            activityMap[activity.id] = activity
          })
          this.activityMap = activityMap
          
          this.initialized = true
        }
      } catch (error) {
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 刷新活动数据
     * 强制重新获取活动列表
     */
    async refreshActivities() {
      this.initialized = false
      return this.initializeActivities()
    },
    
    /**
     * 根据ID获取完整活动对象
     * @param {number} id 活动ID
     * @returns {Object|null} 活动对象
     */
    getActivityById(id) {
      return this.activityMap[id] || null
    },
    
    /**
     * 清除活动数据
     * 在登出时调用
     */
    clearActivities() {
      this.activities = []
      this.activityMap = {}
      this.initialized = false
    }
  }
})